//
//  HouseDetailView.m
//  ThuePhongDep
//
//  Created by Huynh Chi Hung on 8/1/13.
//  Copyright (c) 2013 Huynh Chi Hung. All rights reserved.
//

#import "HouseDetailView.h"
#import "ActivityIndicator.h"
#import "NSURLConnectionWithTag.h"
#import "ImageCache.h"

#define API_SERCRET_KEY @"3eac3f982fd8d14919e92df28efcf0481b294a3efe4e7a987a1ab74ce1d1df80aacf02b57ea1f51057ffae73b9b60b9811eb990459b6c2b7777c0432306fb291"

#define _TAG_SPINNER    3000

#define _TAG_REQUEST_DETAIL_ROOM         3010

@implementation HouseDetailView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        CGFloat colors[8] = {
            0, 0, 0, 0.5,
            0, 0, 0, 0.5
        };
        // Initialization code
        self.margin = UIEdgeInsetsMake(15, 12, 10, 12);
        
        [[self titleBar] setColorComponents:colors];
        self.contentColor = [UIColor colorWithWhite:0.0 alpha:0.8];
        
        // The gradient style (Linear, linear reversed, radial, radial reversed, center highlight). Default = UAGradientBackgroundStyleLinear
        [[self titleBar] setGradientStyle:UAGradientBackgroundStyleLinear];
        
        // The line mode of the gradient view (top, bottom, both, none). Top is a white line, bottom is a black line.
        //        [[self titleBar] setLineMode: pow(2, (arc4random() % 3))];
        
        // The noise layer opacity. Default = 0.4
        //        [[self titleBar] setNoiseOpacity:0.4];
        
        // The header label, a UILabel with the same frame as the titleBar
        [self headerLabel].font = [UIFont boldSystemFontOfSize:floor(self.titleBarHeight / 2.0)];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame title:(NSString*)title houseID:(NSString *)houseID{
    self = [self initWithFrame:frame];
    if (self) {
        self.headerLabel.text = title;
        _houseID = [houseID retain];
        _pageImageView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _pageImageView.pagingEnabled = YES;
        _pageImageView.delegate = self;
        //        _imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        //        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.contentView addSubview:_pageImageView];
        [_pageImageView release];
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:_pageControl];
        _pageControl.numberOfPages = 1;
        [_pageControl setCurrentPage:0];
        [_pageControl release];
        
        //        [_imageView release];
        
        //        spinner = [[UIActivityIndicatorView alloc]
        //                   initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        //        spinner.center = _imageView.center;
        //        [spinner startAnimating];
        //        [_imageView addSubview:spinner];
        //        [spinner release];
        
        _tableView = [[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped] autorelease];
        _tableView.dataSource = self;
        _tableView.delegate = self;
//        _tableView.rowHeight = 60;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundView = nil;
        [self.contentView addSubview:_tableView];
        
        
        [self requestWithhouseID:_houseID];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [_pageImageView setFrame:CGRectMake(0, 0,self.contentView.bounds.size.width, self.contentView.bounds.size.width*2/3)];
    _pageImageView.contentSize = _pageImageView.frame.size;
    [_pageControl setFrame:CGRectMake(0, self.contentView.bounds.size.width*2/3 + 2,self.contentView.bounds.size.width, 5)];
    //    spinner.center = _imageView.center;
    [_tableView setFrame:CGRectMake(0, self.contentView.bounds.size.width*2/3 + 10, self.contentView.bounds.size.width, self.contentView.bounds.size.height - self.contentView.bounds.size.width*2/3 - 13)];
}

- (void)dealloc
{
    [_houseID release];
    [arrayData release];
    [receivedDict release];
    [super dealloc];
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

-(void)requestWithhouseID:(NSString *)houseID
{
    // Create the request.
    NSString *requestURL = [NSString stringWithFormat:@"http://phongdep.vn/ws/house?houseid=%@&secret_key=%@",houseID,API_SERCRET_KEY];
    NSLog(@"%@",requestURL);
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnectionWithTag *connection=[[NSURLConnectionWithTag alloc] initWithRequest:theRequest delegate:self tag:_TAG_REQUEST_DETAIL_ROOM];
    if (connection) {
        if (receivedData) {
            [receivedData release]; // If we've been here before, make sure it's freed.
        }
        receivedData = nil;
        receivedData = [[NSMutableData data] retain];
    } else {
        NSLog(@"connection failed");
        _finishLoad = YES;
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [receivedData appendData:data];
}
/*
 if there is an error occured, this method will be called by connection
 */

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [connection release];
    [receivedData release];
    receivedData = nil;
    NSLog(@"%@" , error);
    _finishLoad = YES;
}

/*
 if data is successfully received, this method will be called by connection
 */

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    NSError *myError = nil;
    NSDictionary *rectDict= [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];
    // show all values
    for(id mainKey in rectDict) {
        NSString *keyAsString = (NSString *)mainKey;
        if ([keyAsString isEqualToString:@"data"]){
            [receivedDict release];
            receivedDict = [(NSDictionary *)[rectDict objectForKey:mainKey] retain];
            if ([[receivedDict allKeys] count] == 0)
                break;
            NSLog(@"%@",receivedDict);
            //            NSArray *imageArray = [receivedDict objectForKey:@"images"];
            NSArray *imageArray = [NSArray arrayWithObject:[receivedDict objectForKey:@"image"]];
            int totalImage =  [imageArray count];
            _pageControl.numberOfPages = totalImage;
            [_pageControl setCurrentPage:0];
            _pageImageView.contentSize = CGSizeMake(_pageImageView.frame.size.width*totalImage, _pageImageView.frame.size.height);
            NSLog(@"Size %f %f",_pageImageView.contentSize.width,_pageImageView.contentSize.height);
            int i = 0;
            for (NSString *imageURL in imageArray) {
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_pageImageView.frame.size.width*i + 5, 0,
                                                                                       _pageImageView.frame.size.width -10, _pageImageView.frame.size.height- 8)];
                imageView.contentMode = UIViewContentModeScaleAspectFit;
                [_pageImageView addSubview:imageView];
                UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
                                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
                spinner.center = imageView.center;
                [spinner startAnimating];
                [imageView addSubview:spinner];
                [spinner release];
                
                if ([[ImageCache sharedImageCache] DoesExist:imageURL] == true) {
                    imageView.image = [[ImageCache sharedImageCache] GetImage:imageURL];
                    [spinner stopAnimating];
                    spinner.hidden = YES;
                }
                else {
                    imageView.image = [UIImage imageNamed:@"default_image"];
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
                    dispatch_async(queue, ^{
                        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
                        UIImage *image = [UIImage imageWithData:data];
                        if (image)
                            [[ImageCache sharedImageCache] AddImage:image withURL:imageURL];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (image) {
                                imageView.image = image;
                                [spinner stopAnimating];
                                spinner.hidden = YES;
                            }
                            else {
                                [spinner stopAnimating];
                                spinner.hidden = YES;
                            }
                        });
                    });
                    
                }
                [imageView release];
                i++;
            }
            
            //            NSString *imageURL = [receivedDict objectForKey:@"image"];
            //            if ([[ImageCache sharedImageCache] DoesExist:imageURL] == true) {
            //
            //                _imageView.image = [[ImageCache sharedImageCache] GetImage:imageURL];
            //                spinner.hidden = YES;
            //                [spinner stopAnimating];
            //            }
            //            else
            //            {
            //                spinner.hidden = NO;
            //                [spinner startAnimating];
            //                _imageView.image = [UIImage imageNamed:@"default_image"];
            //                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
            //                dispatch_async(queue, ^{
            //                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
            //                    UIImage *image = [UIImage imageWithData:data];
            //                    if (image)
            //                        [[ImageCache sharedImageCache] AddImage:image withURL:imageURL];
            //                    dispatch_async(dispatch_get_main_queue(), ^{
            //                        if (image) {
            //                            _imageView.image = image;
            //                            [spinner stopAnimating];
            //                            spinner.hidden = YES;
            //                        }
            //                        else {
            //                        }
            //                    });
            //                });
            //            }
            [_tableView reloadData];
        }
    }
    
    [connection release];
    
    receivedData = nil;
    _finishLoad = YES;
    [[ActivityIndicator currentIndicator] hide];
}

#pragma mark - TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        if (indexPath.row == 0)
            return 60;
        else if (indexPath.row == 0) return 60;
    }
    return 40;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)] autorelease];
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, headerView.frame.size.width-20, 40)] autorelease];
    static NSString* boldFontName = @"Avenir-Black";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:boldFontName size:16];
    label.backgroundColor = [UIColor clearColor];
    if (section  == 0) {
        label.text = @"Thông tin Nhà";
    }
    else if (section == 1) {
        label.text = @"Thông tin liên hệ";
    }
    [headerView addSubview:label];
    return  headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //    if (section == 2) {
    //        return 100;
    //    }
    return 0;
}


- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    //    if (section == 2) {
    //        UIView *footer = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 100)] autorelease];
    //        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, footer.frame.size.width-20, 100)] autorelease];
    //        static NSString* boldFontName = @"Avenir";
    //        label.textColor = [UIColor whiteColor];
    //        label.font = [UIFont fontWithName:boldFontName size:14];
    //        label.numberOfLines = 10;
    //        label.backgroundColor = [UIColor clearColor];
    //        label.text = @"Ngoài những tiện nghi đã có sẵn, với hợp đồng từ 6 tháng trở lên, bạn có thể tuỳ chọn thêm những tiện nghi mới. Việc tuỳ chọn tiện nghi có thể làm thay đổi giá thuê phòng của bạn.";
    //        [footer addSubview:label];
    //        return  footer;
    //    }
    return nil;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section  == 0) {
        return 5; // address, parking, free, description
    }
//    else if (section == 1) {
//        NSDictionary *features = [receivedDict objectForKey:@"features"];
//        if (!features)
//            return 0;
//        id object = [features objectForKey:@"included_features"];
//        if ([object isKindOfClass:[NSArray class]]) {
//            NSArray *includedFeatures = (NSArray*) object;
//            if (includedFeatures)
//                return [includedFeatures count];
//        }
//        else
//            return 0;
//    }
    else if (section == 1) {
        return 3; // name, phone, email
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSString *cellIdentifier = @"UAModalPanelCell";
    //    static NSString* fontName = @"Avenir";
    static NSString* boldFontName = @"Avenir-Black";
    
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        cell.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
        cell.textLabel.font = [UIFont fontWithName:boldFontName size:14];
        cell.textLabel.numberOfLines = 3;
        //        cell.textLabel.minimumFontSize = 10;
        //        cell.textLabel.adjustsFontSizeToFitWidth = YES;
	}
    //	[cell.textLabel setText:[NSString stringWithFormat:@"Row %d", indexPath.row]];
    int section = indexPath.section;
//    NSDictionary *services = [receivedDict objectForKey:@"services"];
    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    numberFormatter.groupingSeparator = @".";
    numberFormatter.decimalSeparator = @",";
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    
	if (section  == 0) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            NSString *address = [receivedDict objectForKey:@"address"];
            NSString *district = [receivedDict objectForKey:@"district"];
            NSString *city = [receivedDict objectForKey:@"city"];
            cell.textLabel.text = [NSString stringWithFormat:@"Địa chỉ: %@, Quận %@, Tỉnh/TP %@.",address,district,city];            
        }
        else if (indexPath.row == 1) {
            cell.textLabel.text = [NSString stringWithFormat:@"Chỗ để xe: %@",
                                   [receivedDict objectForKey:@"parking"]];
        }
        else if (indexPath.row == 2) {
            cell.textLabel.text = [NSString stringWithFormat:@"Phòng trống: %@/%@",
                                   [receivedDict objectForKey:@"free_rooms"],[receivedDict objectForKey:@"total_rooms"]];            
        }        
        else if (indexPath.row == 3) {
            NSString *tmp = @"";
            id object = [receivedDict objectForKey:@"features"];
            if ([object isKindOfClass:[NSDictionary class]]) {
                NSDictionary *features = (NSDictionary*) object;
                for (id key in [features allKeys]) {
                    NSDictionary *dicTmp = [features objectForKey:key];
                    tmp = [tmp stringByAppendingFormat:@",%@",[dicTmp objectForKey:@"name"]];
                }
                cell.textLabel.text = [NSString stringWithFormat:@"Tiện ích chung: %@",tmp];
            }
            else {
                cell.textLabel.text = [NSString stringWithFormat:@"Tiện ích chung:"];
            }
        }
        else if (indexPath.row == 4) {
            if ([receivedDict objectForKey:@"description"] != [NSNull null])
                cell.textLabel.text = [NSString stringWithFormat:@"Mô tả: %@",[receivedDict objectForKey:@"description"]];
            cell.textLabel.text = @"Mô tả:";
        }
    }
    else if (section == 1) {
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        NSDictionary *contactInfo = [receivedDict objectForKey:@"contact"];
        
        if (indexPath.row == 0) {
            cell.textLabel.text = [NSString stringWithFormat:@"Tên: %@",
                                   [contactInfo objectForKey:@"name"]];
        }
        else if (indexPath.row == 1) {
            cell.textLabel.text = [NSString stringWithFormat:@"Phone: %@",
                                   [contactInfo objectForKey:@"phone"]];
        }
        else if (indexPath.row == 2) {
            cell.textLabel.text = [NSString stringWithFormat:@"Email: %@",
                                   [contactInfo objectForKey:@"email"]];
        }
    }
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *contactInfo = [receivedDict objectForKey:@"contact"];
        if (indexPath.row == 1) {
            // Call action
            [self hide];
            [self.parentController.paperFoldView setPaperFoldState:PaperFoldStateDefault];
            NSString *phoneNumber = [@"tel://" stringByAppendingString:[contactInfo objectForKey:@"phone"]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
        }
        else if (indexPath.row == 2) {
            // Email action
            MFMailComposeViewController *mViewController = [[MFMailComposeViewController alloc] init];
            mViewController.mailComposeDelegate = self;
            [mViewController setSubject:@""];
            [mViewController setMessageBody:@"MESSAGE_HERE" isHTML:NO];
            
//            [self x:mViewController animated:YES];
            [mViewController release];

        }
    }
}

#pragma scroolViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    if (sender == _pageImageView) {
        CGFloat pageWidth = _pageImageView.frame.size.width;
        int page = floor((_pageImageView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        _pageControl.currentPage = page;
    }
}

@end
